package com.tang.tasks.zentao;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.intellij.tasks.Task;
import com.intellij.tasks.impl.BaseRepository;
import com.intellij.tasks.impl.BaseRepositoryImpl;
import com.intellij.util.xmlb.annotations.Tag;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Optional;

/**
 *
 * Created by TangZX on 2017/1/10.
 */
@Tag("Zentao")
public class ZentaoTaskRepository extends BaseRepositoryImpl {

    private String sid;

    ZentaoTaskRepository(ZentaoTaskRepositoryType type) {
        super(type);
    }

    private ZentaoTaskRepository(ZentaoTaskRepository other) {
        super(other);
        this.sid = other.sid;
    }

    @Nullable
    @Override
    public Task findTask(@NotNull String s) throws Exception {
        return null;
    }

    @Override
    public Task[] getIssues(@Nullable String query, int offset, int limit, boolean withClosed) throws Exception {
        login();
        Optional<Task[]> optional = Optional.ofNullable(sid)
                .map(sid -> reqAPI("my-bug", new String[]{"sid", sid}))
                .map(r -> r.get("data").getAsString())
                .map(dataString -> (JsonObject)new JsonParser().parse(dataString))
                .map(data -> data.getAsJsonArray("bugs"))
                .map(bugs -> {
                    Task[] tasks = new Task[bugs.size()];
                    for (int i = 0; i < bugs.size(); i++) {
                        JsonObject bug = (JsonObject) bugs.get(i);
                        //System.out.println(bug.toString());
                        tasks[i] = new ZentaoBUG(bug);
                    }
                    return tasks;
                });
        if (optional.isPresent())
            return optional.get();
        return new Task[0];
    }

    void login() {
        if (sid == null) {
            String sid = null;
            JsonObject element = reqAPI("api-getSessionID", new String[0]);
            if (element != null) {
                String data = element.get("data").getAsString();
                //System.out.println("data:"+data);
                JsonParser p = new JsonParser();
                JsonObject dataObject = (JsonObject) p.parse(data);
                sid = dataObject.get("sessionID").getAsString();
            }

            if (sid != null) {
                JsonObject data = reqAPI("user-login", new String[] {
                        "sid", sid,
                        "account", getUsername(),
                        "password", getPassword()
                });
                if (data != null) {
                    JsonObject user = (JsonObject) data.get("user");
                    if (user != null) {
                        this.sid = sid;
                    }
                }
            }
        }
    }

    private JsonObject reqAPI(String api, Object[] params) {
        try {
            String args = "";
            for (int i = 0; i < params.length; i += 2) {
                args = args + String.format("%s=%s&",
                        String.valueOf(params[i]),
                        String.valueOf(params[i + 1]));
            }

            HttpMethod getSidMethod = new GetMethod(String.format("%s/%s.json?%s", getUrl(), api, args));
            int code = this.getHttpClient().executeMethod(getSidMethod);
            if (code == 200) {
                JsonParser p = new JsonParser();
                //System.out.println(getSidMethod.getResponseBodyAsString());
                return (JsonObject) p.parse(getSidMethod.getResponseBodyAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @NotNull
    @Override
    public BaseRepository clone() {
        return new ZentaoTaskRepository(this);
    }
}
